import re
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from erp_system.models import UserModel


class UserRegisterSerializer(ModelSerializer):
    """
    用户的序列化器
    """

    class Meta:
        model = UserModel
        fields = ('id', 'username', 'password', 'real_name', 'phone')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 2,
            },
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 20,
            }
        }

    def validate_phone(self, phone):
        """
        自定义一个验证函数(命名规则:validate_+字段名字)
        验证手机号
        """
        if not phone:
            return phone
        else:
            if not re.match(r'^1[3-9]\d{9}$', phone):
                raise ValidationError('传入的手机号格式有错误!')
        return phone

    def create(self, validated_data):
        user = UserModel.objects.create_user(**validated_data)
        return user
